import json
import re

from find import Find


def get_relationship_items(res_str):
    #  要是你尝试玩弄这段代码的话，你将会在无尽的通宵中不断地咒骂自己为什么会
    #  认为自己聪明到可以优化这段代码。so，现在请关闭这个文件去玩点别的吧。
    if res_str is None:
        return []
    res_str = res_str.strip()
    res_str = re.sub(r"\[[^\]]+\]", "", res_str)
    res_str = re.sub(r"（[^）]+）", "", res_str)
    res_str = re.sub(r"\([^)]+\)", "", res_str)
    if res_str == '':
        return []
    if res_str[len(res_str) - 1] == "等":
        res_str = res_str[:len(res_str) - 2]
    split_set = ['《', '》', '，', ',', '、', '/', '；', ';']
    items = []
    for ss in split_set:
        if ss in res_str:
            if ss == "《" or ss == "》":
                items_t = re.split("[《》]", res_str)
            else:
                items_t = res_str.split(ss)
            for item in items_t:
                item_s = item.strip()
                if item_s != '' and item_s not in split_set:
                    items.append(item_s)
            break
    if len(items) == 0:
        items.append(res_str)
    return items


def get_all_box(filename, outpath):
    boxes = {}
    box_ids = {}
    with open(filename, 'r') as f:
        data = json.load(f)
    for d in data['data']:
        boxes[d['label']] = d
        box_ids[d['label']] = d['id']
    with open(outpath, 'w') as f:
        f.write(json.dumps(box_ids))
    return boxes


def _clean(s):
    if s == "":
        return None
    s = re.sub(r"[\s]+", ",", s)
    return s


def add_to_rs_dict(relationships, s, p, o, f):
    s = _clean(s)
    p = _clean(p)
    o = _clean(o)
    if o == "量子力学史话  出版年":
        print(o)
    if s is None or p is None or o is None:
        return
    #  s = re.sub("：", "", s)
    #  s = re.sub(":", "", s)
    #  s = re.sub(r"[^(\u4e00-\u9fa5)]", "", s)
    #  s = re.sub(r"[\[\]\(\)]", "", s)
    #  p = re.sub("：", "", p)
    #  p = re.sub(":", "", p)
    #  p = re.sub(r"[^(\u4e00-\u9fa5a-zA-z)]", "", p)
    #  p = re.sub(r"[\[\]\(\)]", "", p)
    relationships[(s, p, o)] = f


def parse(label, boxes, depth, ft, parsed, relationships, max_depth):
    #  要是你尝试玩弄这段代码的话，你将会在无尽的通宵中不断地咒骂自己为什么会
    #  认为自己聪明到可以优化这段代码。so，现在请关闭这个文件去玩点别的吧。
    if depth == max_depth:
        return

    if label not in boxes:
        return
    box = boxes[label]

    ty, rs = ft.get_type_relationship(box['attr'])

    if ty is not None:
        add_to_rs_dict(relationships, label, "type", ty, 0)
    for at, at_v in box['attr'].items():
        if rs is None or at not in rs:
            add_to_rs_dict(relationships, label, at, at_v, 0)
    if rs is not None:
        for rs_s_name, rs_a_name in rs.items():
            if rs_s_name not in box['attr']:
                continue
            rs_items = get_relationship_items(box['attr'][rs_s_name])
            for rs_item in rs_items:
                add_to_rs_dict(relationships, label, rs_a_name, rs_item, 1)
                if rs_item not in parsed:
                    parse(rs_item, boxes, depth + 1,
                          ft, parsed, relationships, max_depth)


def all_relationships(boxes_filename, id_dict_output, relationship_output):
    split_sy = "\t"
    relationships = {}
    parsed = {}
    boxes = get_all_box(boxes_filename, id_dict_output)
    ft = Find()
    for label in boxes.keys():
        parsed[label] = 1
        parse(label, boxes, 0, ft, parsed, relationships, 2)
    with open(relationship_output, "w") as f:
        for key, value in relationships.items():
            f.write(key[0] + split_sy + key[1] + split_sy +
                    key[2] + split_sy + str(value) + "\n")
